#include "kernel/nhe.hpp"
#include "yocto/lua/lua-config.hpp"
#include "yocto/code/ipower.hpp"

NHE:: ~NHE() throw()
{
	
}


NHE:: NHE( lua_State *L ) :
Enzyme( L, "NHE", "efficiencyNHE" ),
L0( Lua::Config::Get<lua_Number>(L,"L0") ),
Kr( Lua::Config::Get<lua_Number>(L,"Kr") ),
Kt( Lua::Config::Get<lua_Number>(L,"Kt") ),
C(Kr/Kt),
sH("H+"),
sNa("Na+")
{
    std::cerr << "NHE.L0=" << L0 << std::endl;
    std::cerr << "NHE.Kr=" << Kr << std::endl;
    std::cerr << "NHE.Kt=" << Kt << std::endl;
    std::cerr << "NHE.C =" << C  << std::endl;
}

void NHE:: updateC() { C = Kr/Kt; }

Real NHE:: Sigma( const Real X ) const
{
	const Real Xp1  = 1+X;
	const Real CXp1 = 1+C*X;
	
	const Real num = X*Xp1            + L0 * C * X * CXp1;
	const Real den = L0 * CXp1 * CXp1 + Xp1*Xp1;
		
	return num/den;
}


BIO_PH_ENZYME_CALL(NHE::)
{
	const Real h = S_in[ sH ];
	const Real X = h/Kr;
	
	
	const Real rho = V * Sigma( X ) * efficiency(t);
	
	dS[ sH  ] -= rho;
	dS[ sNa ] += rho;
	
	return rho;
}


Real NHE::omega( const Real h ) const
{
	const Real X = h/Kr;
	//const Real num = 1 + L0 + C * L0 + C*L0*L0 + 2*X * 2*L0*X + 2*C*C*L0*X + 2*C*C*L0*L0*X + X*X + X*X*C*L0 + X*X*L0*C*C + X*X*L0*L0*C*C*C;
	//const Real den = 1 + L0 + 2*X + 2*C*L0*X + X*X + X*X*L0*C*C;	
    
    const Real Xp1  = 1.0+X;
	const Real CXp1 = 1.0+C*X;
	
	const Real num = X*Xp1            + L0 * C * X * CXp1;
	const Real den = L0 * CXp1 * CXp1 + Xp1*Xp1;

    const Real diff_num = C*L0*(C*X+1.0)+(C*C)*L0*X+2*X+1.0;
    const Real diff_den = 2*C*L0*(C*X+1)+2*(X+1);
    
	return (V/Kr) * (diff_num*den - num * diff_den)/(den*den);
	
}

